<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace kitego\services\common;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class SpreadsheetExcelService
{
    private static $instance = null;
    // PHPSpreadsheet实例化对象
    private static $spreadsheet = null;
    // sheet实例化对象
    private static $sheet = null;
    // 表头计数
    protected static $count;
    // 表头占行数
    protected static $topNumber = 3;
    // 表能占据表行的字母对应self::$cellkey
    protected static $cells;
    // 表头数据
    protected static $data = [];
    // 文件名
    protected static $title = '默认文件名';
    // 行宽
    protected static $width = 20;
    // 行高
    protected static $height = 50;
    // 保存文件目录
    protected static $path = './phpExcel/';
    // 设置style
    private static $styleArray = [
        // 'borders' => [
        //     'allBorders' => [
        //           // PHPExcel_Style_Border里面有很多属性，想要其他的自己去看
        //           'style' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK, // 边框是粗的
        //           'style' => \PHPExcel_Style_Border::BORDER_DOUBLE, // 双重的
        //           'style' => \PHPExcel_Style_Border::BORDER_HAIR, // 虚线
        //           'style' => \PHPExcel_Style_Border::BORDER_MEDIUM, // 实粗线
        //           'style' => \PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT, // 虚粗线
        //           'style' => \PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT, // 点虚粗线
        //           'style' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, // 细边框
        //           'color' => ['argb' => 'FFFF0000'],
        //     ],
        // ],
        'font' => [
            'bold' => true
        ],
        'alignment' => [
            'horizontal' => Alignment::HORIZONTAL_CENTER,
            'vertical' => Alignment::VERTICAL_CENTER
        ]
    ];

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    public static function instance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
            self::$spreadsheet = $spreadsheet = new Spreadsheet();
            self::$sheet = $spreadsheet->getActiveSheet();
        }
        
        return self::$instance;
    }

    /**
     * 设置字体格式
     * @param string $title 必选
     */
    public static function setUtf8(string $title)
    {
        return iconv('utf-8', 'gb2312', $title);
    }

    /**
     * 创建保存excel目录
     */
    public static function savePath()
    {
        if (!is_dir(self::$path)) {
            if (!mkdir(self::$path, 0700)) {
                return false;
            }
        }
        
        // 年月一级目录
        $mont_path = self::$path . date('Ym');
        if (!is_dir($mont_path)) {
            if (!mkdir($mont_path, 0700)) {
                return false;
            }
        }
        
        // 日二级目录
        $day_path = $mont_path . '/' . date('d');
        if (!is_dir($day_path)) {
            if (!mkdir($day_path, 0700)) {
                return false;
            }
        }
        
        return $day_path;
    }

    /**
     * 设置标题
     * @param string $title || array ['title'=>'','name'=>'','info'=>[]]
     * @param string $name 
     * @param string $info || array;
     */
    public function setExcelTile(string $title = '', string $name = '', $info = [])
    {
        // 设置参数
        if (is_array($title)) {
            if (isset($title['title'])) $title = $title['title'];
            if (isset($title['name'])) $name = $title['name'];
            if (isset($title['info'])) $info = $title['info'];
        }
        if (empty($title))
            $title = self::$title;
        else
            self::$title = $title;

        if (empty($name)) $name = time();

        // 设置Excel属性
        self::$spreadsheet->getProperties()
            ->setCreator("Neo")
            ->setLastModifiedBy("Neo")
            ->setTitle(self::setUtf8($title))
            ->setSubject($name)
            ->setDescription("")
            ->setKeywords($name)
            ->setCategory("");
        self::$sheet->setTitle($name);
        self::$sheet->setCellValue('A1', $title);
        self::$sheet->setCellValue('A2', self::setCellInfo($info));

        // 文字居中
        self::$sheet->getStyle('A1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        self::$sheet->getStyle('A2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

        // 合并表头单元格
        self::$sheet->mergeCells('A1:' . self::$cells . '1');
        self::$sheet->mergeCells('A2:' . self::$cells . '2');

        self::$sheet->getRowDimension(1)->setRowHeight(40);
        self::$sheet->getRowDimension(2)->setRowHeight(20);

        // 设置表头字体
        self::$sheet->getStyle('A1')->getFont()->setName('黑体');
        self::$sheet->getStyle('A1')->getFont()->setSize(20);
        self::$sheet->getStyle('A1')->getFont()->setBold(true);
        self::$sheet->getStyle('A2')->getFont()->setName('宋体');
        self::$sheet->getStyle('A2')->getFont()->setSize(14);
        self::$sheet->getStyle('A2')->getFont()->setBold(true);

        self::$sheet->getStyle('A3:' . self::$cells . '3')->getFont()->setBold(true);

        return $this;
    }

    /**
     * 设置第二行标题内容
     */
    private static function setCellInfo($info)
    {
        $content = ['操作者：', '导出日期：' . date('Y-m-d', time()), '地址：', '电话：'];
        if (is_array($info) && !empty($info)) {
            if (isset($info['name'])) {
                $content[0] .= $info['name'];
            } else {
                $content[0] .= $info[0] ?? '';
            }
            if (isset($info['site'])) {
                $content[2] .= $info['site'];
            } else {
                $content[2] .= $info[1] ?? '';
            }
            if (isset($info['phone'])) {
                $content[3] .= $info['phone'];
            } else {
                $content[3] .= $info[2] ?? '';
            }

            return implode(' ', $content);
        } else if (is_string($info)) {
            return empty($info) ? implode(' ', $content) : $info;
        }
    }

    /**
     * 设置头部信息
     */
    public static function setExcelHeader(array $data)
    {
        $span = 'A';
        foreach ($data as $value) {
            self::$sheet->getColumnDimension($span)->setWidth(self::$width);
            self::$sheet->setCellValue($span . self::$topNumber, $value);
            $span++;
        }
        self::$sheet->getRowDimension(3)->setRowHeight(self::$height);
        self::$cells = $span;

        return new self;
    }

    /**
     * excl数据导出
     * @param array $data 需要导出的数据
     */
    public function setExcelContent(array $data = [])
    {
        if (!empty($data) && is_array($data)) {
            $span = '';
            $column = self::$topNumber + 1;
            // 行写入
            foreach ($data as $rows) {
                $span = 'A';
                // 列写入
                foreach ($rows as $value) {
                    self::$sheet->setCellValue($span . $column, $value);
                    $span++;
                }
                $column++;
            }
            self::$sheet->getDefaultRowDimension()->setRowHeight(self::$height);
            // 设置内容字体样式
            self::$sheet->getStyle('A1:' . $span . $column)->applyFromArray(self::$styleArray);
            // 设置边框
            self::$sheet->getStyle('A1:' . $span . $column)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
            // 设置自动换行
            self::$sheet->getStyle('A4:' . $span . $column)->getAlignment()->setWrapText(true);
        }

        return new self;
    }

    /**
     * 保存表格数据，直接下载
     * @param string $fileName
     * @param string $suffix 文件后缀名
     * @param bool $isSave 是否保存文件
     */
    public function excelSave(string $fileName = '', string $suffix = 'xlsx', bool $isSave = false)
    {
        if (empty($fileName)) {
            $fileName = date('YmdHis') . time();
        }
        if (empty($suffix)) {
            $suffix = 'xlsx';
        }
        // 重命名表（UTF8编码不需要这一步）
        if (mb_detect_encoding($fileName) != "UTF-8") {
            $fileName = iconv("utf-8", "gbk//IGNORE", $fileName);
        }
        if ($suffix == 'xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            $class = "\PhpOffice\PhpSpreadsheet\Writer\Xlsx";
        } elseif ($suffix == 'xls') {
            header('Content-Type:application/vnd.ms-excel');
            $class = "\PhpOffice\PhpSpreadsheet\Writer\Xls";
        }
        // 清理缓存
        // ob_end_clean();
        $spreadsheet = self::$spreadsheet;
        $writer = new Xlsx($spreadsheet);
        if (!$isSave) {
            // 直接下载
            header('Content-Disposition: attachment;filename="' . $fileName . '.' . $suffix . '"');
            header('Cache-Control: max-age=0');
            $writer->save('php://output');
            // 删除清空 释放内存
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet);
            exit;
        } else {
            // 保存文件
            $path = self::savePath() . '/' . $fileName . '.' . $suffix;
            $writer->save(public_path() . $path);
            // 删除清空 释放内存
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet);

            return $path;
        }
    }

    /**
     * 真实请求导出
     * @param array $header excel表头
     * @param array $titleArr 标题
     * @param array $export 填充数据
     * @param string $filename 保存文件名称
     * @param string $suffix 保存文件后缀
     * @param bool $isSave true|false 是否保存到本地
     */
    public static function export(array $header, array $titleArr, array $export = [], string $filename = '', string $suffix = 'xlsx', bool $isSave = false): array
    {
        $title = !empty($titleArr[0]) ? $titleArr[0] : '导出数据';
        $name = !empty($titleArr[1]) ? $titleArr[1] : '导出数据';
        $info = !empty($titleArr[2]) ? $titleArr[2] : date('Y-m-d H:i:s', time());

        $path = SpreadsheetExcelService::instance()->setExcelHeader($header)
            ->setExcelTile($title, $name, $info)
            ->setExcelContent($export)
            ->excelSave($filename, $suffix, $isSave);
        $path = request()->domain() . $path;

        return [$path];
    }

    /**
     * 使用例子
     */
    public function example() {
        $export = [
            ['question' => '1', 'answer_a' => '2', 'answer_b' => '3', 'answer_c' => '4', 'answer_d' => '5', 'right_answer' => 'A', 'score' => 1],
            ['question' => '2', 'answer_a' => '2', 'answer_b' => '3', 'answer_c' => '4', 'answer_d' => '5', 'right_answer' => 'A', 'score' => 1]
        ];

        $header = ['题目', 'A', 'B', 'C', 'D', '答案', '分值'];
        $title = ['题库', '题库', date('Y-m-d H:i:s', time())];
        $filename = '题库' . date('YmdHis', time());
        $url = SpreadsheetExcelService::export($header, $title, $export, $filename);

        return success($url);
    }
}